package com.bacel.nb.product.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bacel.nb.product.core.domain.Devicedata;
import com.bacel.nb.product.core.dto.ListGageModule;
import com.bacel.nb.product.core.service.IDevicedataService;
import com.bacel.nb.product.core.service.ILogsService;
import com.bacel.nb.product.core.service.ISysmoduleService;
import com.bacel.nb.product.web.template.ViewModel.FreeMarkerView;
import com.bacel.nb.product.web.util.WebUtilify;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.*;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Bacel on 2017/05/02.
 */
@RestController
@RequestMapping(value = "/sysmanage/devicedata", produces = "text/html;charset=UTF-8")
public class devicedataController {
    private final Logger logger = Logger.getLogger(devicedataController.class);

    @Autowired
    private ISysmoduleService sysmoduleService;
    @Autowired
    private IDevicedataService moduleService;
    @Autowired
    private ILogsService logsService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public final ModelAndView list(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String path = request.getContextPath();
        String menulist = WebUtilify.BuildMenuinfo(path, sysmoduleService);
        // 显示首页
        ModelAndView mav = new FreeMarkerView("devicedata/list", "信息", path, menulist, session);
        return mav;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public final ModelAndView add(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String ports = String.valueOf(request.getServerPort());
        if (!ports.equals("80")) {
            ports = ":" + ports;
        }
        String basePath = request.getScheme() + "://" + request.getServerName() + ports;         // 显示首页
        ModelAndView mav = new FreeMarkerView("devicedata/add", "编辑", "", basePath + "/sysmanage/devicedata/list", session);
        return mav;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String edit(@RequestBody Devicedata module, final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        try {
            if (module != null) {

                if (module.getCreatedate() == null)
                    module.setCreatedate(new Timestamp(System.currentTimeMillis()));

                if (module.getId() != null) {
                    module.setCreatedate(new Timestamp(System.currentTimeMillis()));
                    this.moduleService.updateT(module);
                } else {
                    this.moduleService.insertT(module);
                }
            }
        } catch (Exception ex) {
            //logger.error(ex,"editdevicedata","更新渠道错误","");
            errstr = "操作失败001";
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/listdata", method = RequestMethod.GET)
    public String listdata(final HttpServletRequest request)
            throws Exception {

        int pagesize = WebUtilify.parseInt(request.getParameter("rows"), 15);
        int pageindex = WebUtilify.parseInt(request.getParameter("page"), 1);
        String sn = request.getParameter("sn");
        ListGageModule datamodule = new ListGageModule<>();
        datamodule.setPagesize(pagesize);
        datamodule.setPageindex(pageindex);
        Devicedata devicedata = new Devicedata();
        if (!sn.equals("")) {
            devicedata.setSn(sn);
        }
        moduleService.getPageByExampleEq(devicedata, datamodule);
        Map<String, Object> info = new HashMap<>();
        info.put("records", datamodule.getTotalcount());
        info.put("total", datamodule.getPagecount());
        info.put("rows", datamodule.getList());

        String ret = "";
        try {
            ret = JSON.toJSONString(info, SerializerFeature.DisableCircularReferenceDetect);// JSONArray.toJSONString(datamodule);
        } catch (Exception ex) {
            System.out.println("moduledata:" + ex.toString());
        }
        return ret;
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public String del(final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        String idsString = request.getParameter("ids");
        JSONArray idList= JSONArray.parseArray(idsString);
        for (Object id:idList){
            String sid = id.toString();
            int iid=Integer.valueOf(sid);
            this.moduleService.deleteByIdT(iid);
        }
//        if (delid > 0)
//            this.moduleService.deleteByIdT(delid);
//        else {
//            errstr = "传递参数有误";
//        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }


    @RequestMapping(value = "/getDataFile", method = RequestMethod.POST)
    public void getDataFile(final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        Integer dataid = Integer.parseInt(request.getParameter("dataid"));
        Devicedata module = this.moduleService.get(dataid);
        if (module == null) {
            return ;
        }
        byte[] bf =module.getMetadata();
        String filename=module.getId()+module.getSn()+".dat";
        try {
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + bf.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(bf);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping(value = "/getmodule", method = RequestMethod.GET)
    public String getmodule(final HttpServletRequest request)
            throws Exception {
        Integer id = Integer.parseInt(request.getParameter("id"));
        Devicedata module = this.moduleService.get(id);
        if (module != null)
            return JSON.toJSONString(module);
        return "";
    }
}